<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-button :type="btnType1" @click="schedule(1)">班级排课</el-button>
        <el-button :type="btnType2" @click="schedule(2)">教师排课</el-button>
      </el-col>
      <el-col :span="12" style="display: flex; justify-content: flex-end">
        <!-- <el-button-group> -->
        <el-button type="primary" @click="clockShow = true">打卡设置</el-button>
        <el-button type="primary">课时设置</el-button>
        <el-button type="primary">保存更改</el-button>
        <el-button type="primary">发布课程</el-button>
        <!-- </el-button-group> -->
      </el-col>
    </el-row>
    <el-row style="padding: 20px 0">
      <el-button type="primary" @click="view"
        >{{ scheduleType == 1 ? "班级查看" : "教师查看" }}
      </el-button>
      <el-button
        type="primary"
        v-if="scheduleType == 1"
        @click="addClassDialogVisible = true"
        >添加课程
      </el-button>
      <el-button type="primary" v-if="scheduleType == 1">调课记录</el-button>
      <el-button type="primary" v-if="scheduleType == 2">临时调课</el-button>
    </el-row>

    <div
      class="class-table"
      v-loading="loading"
      v-if="queryParams.classId || queryParams.teacherId"
    >
      <div class="table-wrapper">
        <div class="tabel-container">
          <table>
            <thead>
              <tr>
                <th>
                  <div class="out">
                    <!-- <span>星期</span> -->
                    <span>时间</span>
                  </div>
                </th>
                <th v-for="(weekNum, weekIndex) in weeks" :key="weekIndex">
                  星期{{ digital2Chinese(weekNum + 1, "week") }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(courseNum, courseIndex) in coursesLen"
                :key="courseIndex"
              >
                <td>
                  <p>{{ "第" + digital2Chinese(courseNum) + "节" }}</p>
                  <p class="period">{{ classTableData.period[courseIndex] }}</p>
                </td>

                <td
                  :style="{
                    backgroundColor:
                      fieldCharacter(weekIndex, courseIndex, 'type') != null
                        ? fieldCharacter(weekIndex, courseIndex, 'type') == 1
                          ? '#0ab1f1'
                          : '#f7f72d'
                        : '#f5f5f5',
                  }"
                  :type="fieldCharacter(weekIndex, courseIndex, 'type')"
                  v-for="(weekNum, weekIndex) in weeks"
                  @click="courseClick(weekIndex, courseIndex)"
                  :key="weekIndex"
                  style="cursor: pointer; position: relative"
                  class="cell"
                >
                  <p>
                    {{ fieldCharacter(weekIndex, courseIndex, "subjectName") }}
                  </p>
                  <p>
                    {{ fieldCharacter(weekIndex, courseIndex, "roomName") }}
                  </p>
                  <p>
                    {{ fieldCharacter(weekIndex, courseIndex, "teacherName") }}
                  </p>
                  <!--                  <p>{{ fieldCharacter(weekIndex, courseIndex, "type") }}</p>-->

                  <i
                    class="el-icon-close close"
                    v-if="fieldCharacter(weekIndex, courseIndex, 'subjectId')"
                    style="
                      position: absolute;
                      top: 3px;
                      right: 3px;
                      font-size: 24px;
                    "
                    @click.stop="
                      deleteSubject(fieldCharacter(weekIndex, courseIndex, ''))
                    "
                  ></i>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <el-dialog
      :title="scheduleType == 1 ? '选择班级' : '选择教师'"
      :visible.sync="dialogVisible"
      width="80%"
      append-to-body
      :before-close="cancel"
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="form" :model="form" :inline="true" label-width="50px">
          <el-form-item label="学院" prop="collegeId">
            <college-selector v-model="form.collegeId"></college-selector>
          </el-form-item>
          <el-form-item
            label="系部"
            prop="departmentsId"
            v-if="scheduleType == 1"
          >
            <departments-selector
              v-model="form.departmentsId"
              :college-id="form.collegeId"
            ></departments-selector>
          </el-form-item>
          <el-form-item
            label="专业"
            prop="professionId"
            v-if="scheduleType == 1"
          >
            <professions-selector
              v-model="form.professionId"
              :department-id="form.departmentsId"
            ></professions-selector>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置
            </el-button>
          </el-form-item>
        </el-form>
        <div style="display: flex; flex-flow: wrap">
          <el-tag
            v-for="(it, index) in classList"
            :key="index"
            style="flex: 0 0 10%; margin: 10px; text-align: center"
            @click="selectClass(it)"
            >{{ scheduleType == 1 ? it.classesName : it.teacherName }}
          </el-tag>
        </div>
        <div style="text-align: center" v-if="classList.length == 0">
          <el-empty description="暂无数据"></el-empty>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <schedule-dialog
      :show.sync="scheduleDialogVisible"
      @success="getList"
      ref="schedule"
    />
    <add-class-dialog
      :show.sync="addClassDialogVisible"
      @success="getList"
      ref="addClass"
    />
    <!-- 课时设置 -->
    <lesson-setting :show.sync="addLessonDialogVisible" />
    <!-- 打卡设置 -->
    <clock-setting :show.sync="clockShow"></clock-setting>
  </div>
</template>

<script>
import {
  getClassTimetablePageByClassId,
  getClassTimetablePageByTeacherId,
  timeAllList,
  deleteClassTimetable,
} from "@/api/study/classTimetable";
import common from "@/api/collegebase/common";
import ScheduleDialog from "./scheduleDialog.vue";
import AddClassDialog from "./addClass.vue";
import { getClassesPage } from "@/api/collegebase/classes";
import { getTeacherTeachersPage, getTeacherTeachersList } from "@/api/collegebase/teacherTeachers";
import CollegeSelector from "@/components/CollegeSelector";
import DepartmentsSelector from "@/components/DepartmentsSelector";
import ProfessionsSelector from "@/components/ProfessionsSelector";
import LessonSetting from "./lessonSetting.vue";
import clockSetting from "./clockSetting.vue";
export default {
  components: {
    ProfessionsSelector,
    DepartmentsSelector,
    CollegeSelector,
    ScheduleDialog,
    AddClassDialog,
    LessonSetting,
    clockSetting
  },

  data() {
    return {
      addClassDialogVisible: false,
      scheduleDialogVisible: false,
      addLessonDialogVisible: false,
      form: { professionId: "" },

      dialogVisible: false,
      btnType1: "primary",
      btnType2: "",
      weeks: [
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
        "星期天",
      ], //周集合
      coursesLen: 0, //最大课节数
      classTableData: {
        //mock模拟的数据
        period: [
          "08:00-09:00",
          "09:00-10:00",
          "10:00-11:00",
          "11:00-12:00",
          "13:00-14:00",
          "14:00-15:00",
          "15:00-16:00",
          "16:00-17:00",
          "18:00-19:00",
          "20:00-21:00",
          "21:00-22:00",
        ], //时间段
        weekCourse: [
          {
            week: 0,
            courses: [
              { index: 1, subjectName: "物理" },
              { index: 3, subjectName: "语文" },
            ],
          },
          {
            week: 1,
            courses: [
              { index: 3, subjectName: "生物" },
              { index: 4, subjectName: "语文" },
              { index: 5, subjectName: "历史" },
              { index: 6, subjectName: "数学" },
              { index: 7, subjectName: "英语" },
              { index: 8, subjectName: "生物" },
              { index: 1, subjectName: "生物" },
            ],
          },
          {
            week: 2,
            courses: [
              { index: 3, subjectName: "生物" },
              { index: 4, subjectName: "语文" },
              { index: 5, subjectName: "历史" },
              { index: 6, subjectName: "数学" },
              { index: 7, subjectName: "英语" },
              { index: 8, subjectName: "生物" },
              { index: 1, subjectName: "生物" },
            ],
          },
          {
            week: 3,
            courses: [
              { index: 5, subjectName: "英语" },
              { index: 6, subjectName: "英语" },
              { index: 7, subjectName: "物理" },
              { index: 8, subjectName: "英语" },
              { index: 1, subjectName: "生物" },
              { index: 2, subjectName: "数学" },
              { index: 3, subjectName: "英语" },
              { index: 9, subjectName: "英语" },
              { index: 10, subjectName: "英语" },
              { index: 11, subjectName: "英语" },
            ],
          },
          {
            week: 4,
            courses: [
              { index: 4, title: "语文" },
              { index: 5, title: "英语" },
              { index: 6, title: "生物" },
              { index: 7, title: "历史" },
            ],
          },
          {
            week: 5,
            courses: [
              { index: 8, title: "化学" },
              { index: 1, title: "英语" },
            ],
          },
          {
            week: 6,
            courses: [
              { index: 8, title: "化学" },
              { index: 1, title: "英语" },
            ],
          },
        ],
      },
      teacherClass: {},
      queryParams: {

        weekId: null,
      },
      classList: [],
      scheduleType: 1,
      clockShow: false
    };
  },
  created() {
    this.updateData();
    this.initWeekCourses();
    this.getList();
    this.getTime();
    this.getData();
  },
  methods: {
    view() {
      this.classList = [];
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.scheduleType == 1) {
          //获取所有班级数据
          getClassesPage({ pageNo: 1, pageSize: 99 }).then((res) => {
            this.classList = res.data.list;
          });
        } else if (this.scheduleType == 2) {
          //获取所有教师数据
          getTeacherTeachersPage({ pageNo: 1, pageSize: 99 }).then((res) => {
            this.classList = res.data.list;
          });
        }
      });
    },
    deleteSubject(e) {
      console.log(e);
      this.$confirm("此操作将删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteClassTimetable({
            classesId: e.classesId,
            studyTimeId: e.studyTimeId,
            weekId: e.weekId,
          });
          //  console.log('res',res)
          if (res.data) {
            this.getList();
            this.$forceUpdate();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //班级选择
    selectClass(e) {
      console.info('选择的班级', e);
      this.queryParams = {
        classId: undefined,
        teacherId: undefined,
        collegeId: undefined
      };
      this.queryParams.collegeId = e.collegeId;
      if (this.scheduleType == 1) {
        this.queryParams.classId = e.id;
      }
      if (this.scheduleType == 2) {
        this.queryParams.teacherId = e.id;
      }
      this.dialogVisible = false;
      this.getList();
    },
    handleQuery() {
      console.log(this.form);
      if (this.scheduleType == 1) {
        common.getClassesList(this.form.professionId).then((res) => {
          // console.log(res)
          this.classList = res.data;
        });
      } else if (this.scheduleType == 2) {
        getTeacherTeachersList({ collegeId: this.form.collegeId }).then((res) => {
          this.classList = res.data;
        });

      }
    },
    resetQuery() {
      this.form = {
        professionId: "",
        departmentsId: "",
        collegeId: "",
      };
      common.getClassesList(this.form.professionId).then((res) => {
        // console.log(res)
        this.classList = res.data;
      });
    },

    //获取学院
    async getData() {

    },
    schedule(flag) {
      this.scheduleType = flag;
      if (flag == 1) {
        this.btnType1 = "primary";
        this.btnType2 = "";
      } else {
        this.btnType1 = "";
        this.btnType2 = "primary";
      }
    },
    courseClick(weekIndex, courseIndex) {
      if (
        this.classTableData.weekCourse[weekIndex] &&
        this.classTableData.weekCourse[weekIndex].courses[courseIndex] &&
        this.classTableData.weekCourse[weekIndex].courses[courseIndex].index ===
        courseIndex + 1
      ) {
        this.scheduleDialogVisible = true;
        this.$refs.schedule.initData(
          JSON.stringify(this.classTableData.weekCourse[weekIndex].courses[courseIndex])
        );
        console.log(`周${weekIndex}  第${courseIndex + 1}节课`);
        console.log(
          this.classTableData.weekCourse[weekIndex].courses[courseIndex]
        );
        let detail = this.classTableData.weekCourse[weekIndex].courses[courseIndex]
        let url = `subjectId=${detail.subjectId}&studyTimeId=${detail.studyTimeId}&weekId=${detail.weekId}`
        console.log("url", url);
        // return this.classTableData.weekCourse[weekIndex].courses[courseIndex]
        //   .subjectName;
      }
    },
    getTime() {
      this.classTableData.period = [];
      timeAllList().then((res) => {
        res.data.forEach((e) => {
          this.classTableData.period.push(e.beginTime + "-" + e.endTime);
        });
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;

      if (this.queryParams.classId) {
        // 执行查询
        getClassTimetablePageByClassId(this.queryParams).then((response) => {
          let list = response.data;
          if (response.code == 2001001012) {
            this.getList();
            return;
          }
          let week = [];
          let data = [];
          // list.forEach((e, i) => {
          //   //每7个元素放进week二维数组
          //   if (i % 11 == 0) {
          //     week.push(list.slice(i, i + 11));
          //   }
          // });
          // for (let i = 0; i < 7; i++) {
          //   data.push({
          //     week: i,
          //     courses: week[i],
          //   });
          // }

          // week.forEach((e) => {
          //   e.forEach((r, i) => {
          //     r.index = i + 1;
          //   });
          // });
          for (let i = 0; i < 7; i++) {
            let hours = [];
            for (let j = 0; j < 11; j++) {
              hours.push({ "weekId": i + 1, "studyTimeId": j + 1, "classesId": this.queryParams.classId, "collegeId": this.queryParams.collegeId, subjectId: null, });
            }
            week.push(hours)
          }
          week.forEach(w => {
            w.forEach((r, i) => {
              list.forEach(item => {

                if (item.weekId == r.weekId && item.studyTimeId == r.studyTimeId && item.roomId) {

                  w[i] = item;
                  w[i]["index"] = i + 1;
                }
              })
              r.index = i + 1;
            })
          })
          for (let i = 0; i < 7; i++) {
            data.push({
              week: i,
              courses: week[i],
            });
          }
          this.classTableData.weekCourse = data;
          this.$forceUpdate();

          // console.log(list);
          this.total = response.data.total;
          this.loading = false;
        });
      } else if (this.queryParams.teacherId) {

        getClassTimetablePageByTeacherId(this.queryParams).then((response) => {
          let list = response.data;
          // 执行查询
          let week = [];
          let data = [];

          for (let i = 0; i < 7; i++) {
            let hours = [];
            for (let j = 0; j < 11; j++) {
              hours.push({ "weekId": i + 1, "studyTimeId": j + 1, "teacherId": this.queryParams.teacherId, "collegeId": this.queryParams.collegeId, subjectId: null, });
            }
            week.push(hours)
          }
          week.forEach(w => {
            w.forEach((r, i) => {
              list.forEach(item => {
                if (item.weekId == r.weekId && item.studyTimeId == r.studyTimeId) {
                  w[i] = item;
                  w[i]["index"] = i + 1;
                }
              })
              r.index = i + 1;
            })
          })
          for (let i = 0; i < 7; i++) {
            data.push({
              week: i,
              courses: week[i],
            });
          }
          this.classTableData.weekCourse = data;
          this.$forceUpdate();

          // console.log(list);
          // this.total = response.data.total;
          this.total = 49;
          this.loading = false;
        });
      }


    },

    /**
     * 更新mock模拟的数据，对数据进行排序
     */
    updateData() {
      /* 将数据按从周日到周六排序 */
      this.classTableData.weekCourse.sort((a, b) => {
        return a.week - b.week;
      });

      /* 将数据按从第一节到第n节排序 */
      for (let v of this.classTableData.weekCourse) {
        for (let k in v) {
          if (k === "courses") {
            v[k].sort((a, b) => {
              return a.index - b.index;
            });
          }
        }
      }

      // console.log(JSON.stringify(this.classTableData.weekCourse));
    },
    /**
     * 计算周数据及课节数
     */
    initWeekCourses() {
      const that = this;
      this.weeks = []; //周集合
      this.coursesLen = 0; //最大的课节数

      this.weeks = this.classTableData.weekCourse.map((item, index) => {
        // console.log("item", item);
        for (let k in item) {
          if (k === "courses") {
            let maxCoursesLen = 0;
            /* 取出一周中最大的课节数及当天的最大课节数 */
            for (let j of item[k]) {
              j.index > that.coursesLen && (that.coursesLen = j.index); //取所有一周里最大课节值
              j.index > maxCoursesLen && (maxCoursesLen = j.index); //取当天最大课节值
            }

            /* 如果当天的课节总数小于当天的最大课节值 */
            if (item[k].length < maxCoursesLen) {
              for (let i = 0; i < maxCoursesLen; i++) {
                //以最大课节值为终点遍历当天课节
                if (!item[k][i] || item[k][i].index != i + 1) {
                  //如果下标课节不存在或着与循环的下标不匹配
                  item[k].splice(i, 0, ""); //填充空课节
                }
              }
            }
          }
        }
        return item.week;
      });

      // console.log(JSON.stringify(this.classTableData.weekCourse));
    },
    /**
     * 处理格子数据，无数据转换为字符串'-'
     * @param {Number} weekIndex 周几对应的下标
     * @param {Number} courseNum 第几节课对应的下标
     * @returns {String} 返回对应的字符
     */
    fieldCharacter(weekIndex, courseIndex, name) {

      if (
        this.classTableData.weekCourse[weekIndex] &&
        this.classTableData.weekCourse[weekIndex].courses[courseIndex] &&
        this.classTableData.weekCourse[weekIndex].courses[courseIndex].index ===
        courseIndex + 1
      ) {

        if (!name) {
          return this.classTableData.weekCourse[weekIndex].courses[courseIndex];
        } else {
          return this.classTableData.weekCourse[weekIndex].courses[courseIndex][
            name
          ];
        }
      }
      return "-";
    },

    /**
     * 数字转中文
     * @param {Number} num 需要转换的数字
     * @param {Boolean} identifier 标识符
     * @returns {String} 转换后的中文
     */
    digital2Chinese(num, identifier) {
      const character = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
        "十",
        "十一",
        "十二",
      ];
      return identifier === "week" && (num === 0 || num === 7)
        ? "日"
        : character[num];
    },

    cancel() {
      this.form = {
        collegeId: undefined,
        departmentsId: undefined,
        professionId: undefined,
      },
        this.dialogVisible = false;
    }
  },
};
</script>

<style lang="scss" scoped>
.close {
  display: none;
}

.cell:hover {
  .close {
    display: block;
    position: absolute;
    top: 3px;
    right: 3px;
  }
}

.close:hover {
  display: block;
}

.class-table {
  .table-wrapper {
    width: 100%;
    height: 100%;
    overflow: auto;
  }

  .tabel-container {
    /* margin: 7px; */

    table {
      table-layout: fixed;
      width: 100%;

      thead {
        background-color: #67a1ff;

        th {
          color: #fff;
          line-height: 17px;
          font-weight: normal;
        }
      }

      tbody {
        /* background-color: #eaf2ff; */
        background-color: #f5f5f5;

        td {
          color: #000;
          line-height: 12px;
        }
      }

      th,
      td {
        width: 60px;
        padding: 12px 2px;
        font-size: 12px;
        text-align: center;
      }

      tr td:first-child {
        color: #333;

        .period {
          font-size: 8px;
        }
      }
    }
  }
}
</style>
